package com.zone.gateway.core.socket;

import com.zone.gateway.core.session.Configuration;
import com.zone.gateway.core.socket.handler.AuthorizationHandler;
import com.zone.gateway.core.socket.handler.ProtoDataHandler;
import com.zone.gateway.core.session.GatewaySessionFactory;
import com.zone.gateway.core.socket.handler.GatewayChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

/**
 * @author: zongzi
 * @description: 会话管道初始化器
 * @date: 2025/4/17
 */
public class SessionChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final Configuration configuration;
    private final GatewaySessionFactory gatewaySessionFactory;

    public SessionChannelInitializer(GatewaySessionFactory gatewaySessionFactory, Configuration configuration) {
        this.configuration = configuration;
        this.gatewaySessionFactory = gatewaySessionFactory;
    }
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        // http request 解码器，就能在自定义handler中直接获取到Http request请求信息，无需读取ByteBuf
        pipeline.addLast(new HttpRequestDecoder());
        // http response 编码器，就能在自定义handler write response 无需 write ByteBuf
        pipeline.addLast(new HttpResponseEncoder());
        /*
         * HttpObjectAggregator 是 Netty 网络框架中的一个关键解码器（Handler），
         * 用于将 HTTP 请求或响应的多个分片（如 HttpRequest、HttpContent、LastHttpContent）
         * 聚合成一个完整的 FullHttpRequest 或 FullHttpResponse，
         * 简化了 HTTP 消息的处理流程。以下是它的详细解析和使用
         * 解决 TCP 粘包/拆包问题：HTTP 消息可能被拆分成多个数据包传输。
         * 聚合 HTTP 消息：将分散的 HttpObject（如请求头、内容体）合并为完整的 FullHttpRequest/FullHttpResponse。
         * 避免手动处理分块数据：开发者无需关心分片逻辑，直接处理完整消息。
         * */
        pipeline.addLast(new HttpObjectAggregator(5 * 1024 * 1024));
        // 自定义session handler，由HttpObjectAggregator，就能直接在自定义Handler中拿到FullHttpRequest
        pipeline.addLast(new GatewayChannelHandler(configuration));
        pipeline.addLast(new AuthorizationHandler(configuration));
        pipeline.addLast(new ProtoDataHandler(gatewaySessionFactory));
    }
}
